import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import QtQuick.Window 2.15

ApplicationWindow {
    id: root
    width: Screen.width > 1000 ? 1600 : 800
    height: Screen.height > 1000 ? 1000 : 900
    visible: true
    title: "气泡组件示例"
    
    readonly property real scaleFactor: width > 1000 ? 1.8 : 1.5
    
    // 状态
    property string statusText: "就绪"
    
    // 气泡包装组件（延迟创建）
    property var bubbleWrapper: null
    
    // 创建气泡包装组件
    function createBubbleWrapper() {
        if (bubbleWrapper) {
            console.log("BubbleWrapper already exists")
            return
        }
        
        console.log("Creating BubbleWrapper component...")
        var component = Qt.createComponent("BubbleWrapper.qml")
        console.log("Component status: " + component.status + " (Ready=" + Component.Ready + ")")
        
        if (component.status === Component.Ready) {
            bubbleWrapper = component.createObject(root)
            console.log("BubbleWrapper created: " + bubbleWrapper)
            
            if (bubbleWrapper) {
                // 连接信号
                bubbleWrapper.aboutToShow.connect(function() {
                    statusText = "气泡即将显示"
                })
                bubbleWrapper.aboutToClose.connect(function() {
                    statusText = "气泡即将关闭"
                })
                bubbleWrapper.animationStarted.connect(function() {
                    statusText = "气泡动画开始"
                })
                bubbleWrapper.animationFinished.connect(function() {
                    statusText = "气泡动画完成"
                })
                bubbleWrapper.animationStopped.connect(function() {
                    statusText = "气泡动画停止"
                })
                
                // 同步初始文本和设置
                if (bubbleWrapper.bubbleWidget) {
                    bubbleWrapper.bubbleWidget.text = textEdit.text
                    bubbleWrapper.bubbleWidget.direction = directionCombo.currentIndex
                    bubbleWrapper.bubbleWidget.triangleSize = Qt.size(triangleWidthSpin.value, triangleHeightSpin.value)
                    bubbleWrapper.bubbleWidget.fontSize = fontSizeSpin.value
                    bubbleWrapper.bubbleWidget.borderRadius = Math.round(borderRadiusSlider.value)
                    bubbleWrapper.bubbleWidget.textMargin = Math.round(textMarginSlider.value)
                    bubbleWrapper.bubbleWidget.penColor = penColorButton.text
                    bubbleWrapper.bubbleWidget.brushColor = brushColorButton.text
                    bubbleWrapper.bubbleWidget.textColor = textColorButton.text
                }
                
                // 同步动画设置
                bubbleWrapper.animationDuration = animationSwitch.checked ? animationDurationSlider.value : 0
                
                statusText = "气泡组件就绪"
                console.log("BubbleWrapper signals connected, statusText=" + statusText)
            } else {
                statusText = "气泡创建失败"
                console.log("BubbleWrapper creation failed")
            }
        } else {
            statusText = "气泡组件加载失败: " + component.errorString()
            console.log("BubbleWrapper component load failed: " + component.errorString())
        }
    }
    
    Component.onCompleted: {
        // 延迟创建气泡组件
        Qt.callLater(function() {
            createBubbleWrapper()
        })
    }
    
    ColumnLayout {
        anchors.fill: parent
        spacing: 12 * scaleFactor
        anchors.margins: 12 * scaleFactor
        
        // 状态标签
        Text {
            id: statusLabel
            Layout.fillWidth: true
            Layout.preferredHeight: 50 * scaleFactor
            text: root.statusText
            font.pixelSize: 20 * scaleFactor
            horizontalAlignment: Text.AlignHCenter
            verticalAlignment: Text.AlignVCenter
            color: "#333333"
            Rectangle {
                anchors.fill: parent
                border.color: "#CCCCCC"
                border.width: 1
                color: "transparent"
            }
        }
        
        ScrollView {
            Layout.fillWidth: true
            Layout.fillHeight: true
            
            ColumnLayout {
                width: parent.width
                spacing: 12 * scaleFactor
                
                // 文本设置
                GridLayout {
                    Layout.fillWidth: true
                    columns: 2
                    columnSpacing: 12 * scaleFactor
                    rowSpacing: 12 * scaleFactor
                    
                    Text {
                        text: "文本："
                        font.pixelSize: 18 * scaleFactor
                        Layout.preferredWidth: 120 * scaleFactor
                    }
                    TextField {
                        id: textEdit
                        Layout.fillWidth: true
                        Layout.preferredHeight: 45 * scaleFactor
                        text: "你好！"
                        font.pixelSize: 18 * scaleFactor
                        onTextChanged: {
                            if (bubbleWrapper && bubbleWrapper.bubbleWidget) {
                                bubbleWrapper.bubbleWidget.text = text
                            }
                        }
                        Component.onCompleted: {
                            // 初始化时同步文本
                            if (bubbleWrapper && bubbleWrapper.bubbleWidget) {
                                bubbleWrapper.bubbleWidget.text = text
                            }
                        }
                    }
                }
                
                // 方向设置
                GridLayout {
                    Layout.fillWidth: true
                    columns: 4
                    columnSpacing: 12 * scaleFactor
                    rowSpacing: 12 * scaleFactor
                    
                    Text {
                        text: "方向："
                        font.pixelSize: 18 * scaleFactor
                        Layout.preferredWidth: 120 * scaleFactor
                    }
                    ComboBox {
                        id: directionCombo
                        model: ["右", "左", "下", "上"]
                        currentIndex: 3  // 默认选中"上"
                        font.pixelSize: 18 * scaleFactor
                        Layout.preferredWidth: 120 * scaleFactor
                        Layout.preferredHeight: 45 * scaleFactor
                        onCurrentIndexChanged: {
                            if (bubbleWrapper && bubbleWrapper.bubbleWidget) {
                                bubbleWrapper.bubbleWidget.direction = currentIndex
                            }
                        }
                    }
                    Item { Layout.fillWidth: true }
                    Item { Layout.fillWidth: true }
                    
                    Text {
                        text: "三角形宽度："
                        font.pixelSize: 18 * scaleFactor
                        Layout.preferredWidth: 120 * scaleFactor
                    }
                    RowLayout {
                        Layout.fillWidth: true
                        SpinBox {
                            id: triangleWidthSpin
                            from: 0
                            to: 50
                            value: 10
                            font.pixelSize: 18 * scaleFactor
                            Layout.preferredWidth: 100 * scaleFactor
                            Layout.preferredHeight: 45 * scaleFactor
                            onValueChanged: {
                                if (bubbleWrapper && bubbleWrapper.bubbleWidget) {
                                    var triSize = bubbleWrapper.bubbleWidget.triangleSize
                                    bubbleWrapper.bubbleWidget.triangleSize = Qt.size(value, triSize.height)
                                }
                            }
                        }
                        Text {
                            text: "像素"
                            font.pixelSize: 18 * scaleFactor
                        }
                    }
                    Text {
                        text: "三角形高度："
                        font.pixelSize: 18 * scaleFactor
                        Layout.preferredWidth: 120 * scaleFactor
                    }
                    RowLayout {
                        Layout.fillWidth: true
                        SpinBox {
                            id: triangleHeightSpin
                            from: 0
                            to: 50
                            value: 10
                            font.pixelSize: 18 * scaleFactor
                            Layout.preferredWidth: 100 * scaleFactor
                            Layout.preferredHeight: 45 * scaleFactor
                            onValueChanged: {
                                if (bubbleWrapper && bubbleWrapper.bubbleWidget) {
                                    var triSize = bubbleWrapper.bubbleWidget.triangleSize
                                    bubbleWrapper.bubbleWidget.triangleSize = Qt.size(triSize.width, value)
                                }
                            }
                        }
                        Text {
                            text: "像素"
                            font.pixelSize: 18 * scaleFactor
                        }
                    }
                }
                
                // 字体设置
                GridLayout {
                    Layout.fillWidth: true
                    columns: 3
                    columnSpacing: 12 * scaleFactor
                    rowSpacing: 12 * scaleFactor
                    
                    Text {
                        text: "字体大小："
                        font.pixelSize: 18 * scaleFactor
                        Layout.preferredWidth: 120 * scaleFactor
                    }
                    RowLayout {
                        Layout.fillWidth: true
                        SpinBox {
                            id: fontSizeSpin
                            from: 8
                            to: 30
                            value: 15
                            font.pixelSize: 18 * scaleFactor
                            Layout.preferredWidth: 100 * scaleFactor
                            Layout.preferredHeight: 45 * scaleFactor
                            onValueChanged: {
                                if (bubbleWrapper && bubbleWrapper.bubbleWidget) {
                                    bubbleWrapper.bubbleWidget.fontSize = value
                                }
                            }
                        }
                        Text {
                            text: "像素"
                            font.pixelSize: 18 * scaleFactor
                        }
                    }
                    Item { Layout.fillWidth: true }
                }
                
                // 样式设置
                GridLayout {
                    Layout.fillWidth: true
                    columns: 3
                    columnSpacing: 12 * scaleFactor
                    rowSpacing: 12 * scaleFactor
                    
                    Text {
                        text: "边框圆角："
                        font.pixelSize: 18 * scaleFactor
                        Layout.preferredWidth: 120 * scaleFactor
                    }
                    Slider {
                        id: borderRadiusSlider
                        from: 0
                        to: 30
                        value: 5
                        Layout.fillWidth: true
                        Layout.preferredHeight: 45 * scaleFactor
                        onValueChanged: {
                            borderRadiusLabel.text = Math.round(value) + " 像素"
                            if (bubbleWrapper && bubbleWrapper.bubbleWidget) {
                                bubbleWrapper.bubbleWidget.borderRadius = Math.round(value)
                            }
                        }
                    }
                    Text {
                        id: borderRadiusLabel
                        text: "5 像素"
                        font.pixelSize: 18 * scaleFactor
                        Layout.preferredWidth: 80 * scaleFactor
                    }
                    
                    Text {
                        text: "文本边距："
                        font.pixelSize: 18 * scaleFactor
                        Layout.preferredWidth: 120 * scaleFactor
                    }
                    Slider {
                        id: textMarginSlider
                        from: 0
                        to: 30
                        value: 8
                        Layout.fillWidth: true
                        Layout.preferredHeight: 45 * scaleFactor
                        onValueChanged: {
                            textMarginLabel.text = Math.round(value) + " 像素"
                            if (bubbleWrapper && bubbleWrapper.bubbleWidget) {
                                bubbleWrapper.bubbleWidget.textMargin = Math.round(value)
                            }
                        }
                    }
                    Text {
                        id: textMarginLabel
                        text: "8 像素"
                        font.pixelSize: 18 * scaleFactor
                        Layout.preferredWidth: 80 * scaleFactor
                    }
                    
                    Text {
                        text: "边框颜色："
                        font.pixelSize: 18 * scaleFactor
                        Layout.preferredWidth: 120 * scaleFactor
                    }
                    RowLayout {
                        Layout.fillWidth: true
                        Layout.columnSpan: 2
                        spacing: 8 * scaleFactor
                        Button {
                            id: penColorButton
                            Layout.fillWidth: true
                        Layout.preferredHeight: 50 * scaleFactor
                        text: "#DBBA92"
                        font.pixelSize: 16 * scaleFactor
                        onClicked: {
                                colorDialog.targetButton = penColorButton
                                colorDialog.isPenColor = true
                                colorDialog.isTextColor = false
                                colorDialog.currentColor = penColorButton.text
                                colorInput.text = penColorButton.text
                                colorDialog.open()
                        }
                        background: Rectangle {
                            color: penColorButton.text
                            border.color: "#CCCCCC"
                            border.width: 2
                            }
                        }
                    }
                    
                    Text {
                        text: "背景颜色："
                        font.pixelSize: 18 * scaleFactor
                        Layout.preferredWidth: 120 * scaleFactor
                    }
                    RowLayout {
                        Layout.fillWidth: true
                        Layout.columnSpan: 2
                        spacing: 8 * scaleFactor
                        Button {
                            id: brushColorButton
                            Layout.fillWidth: true
                        Layout.preferredHeight: 50 * scaleFactor
                        text: "#FFF8F0"
                        font.pixelSize: 16 * scaleFactor
                        onClicked: {
                                colorDialog.targetButton = brushColorButton
                                colorDialog.isPenColor = false
                                colorDialog.isTextColor = false
                                colorDialog.currentColor = brushColorButton.text
                                colorInput.text = brushColorButton.text
                                colorDialog.open()
                        }
                        background: Rectangle {
                            color: brushColorButton.text
                            border.color: "#CCCCCC"
                            border.width: 2
                            }
                        }
                    }
                    
                    Text {
                        text: "文本颜色："
                        font.pixelSize: 18 * scaleFactor
                        Layout.preferredWidth: 120 * scaleFactor
                    }
                    RowLayout {
                        Layout.fillWidth: true
                        Layout.columnSpan: 2
                        spacing: 8 * scaleFactor
                        Button {
                            id: textColorButton
                            Layout.fillWidth: true
                        Layout.preferredHeight: 50 * scaleFactor
                        text: "#DBBA92"
                        font.pixelSize: 16 * scaleFactor
                        onClicked: {
                                colorDialog.targetButton = textColorButton
                                colorDialog.isPenColor = false
                                colorDialog.isTextColor = true
                                colorDialog.currentColor = textColorButton.text
                                colorInput.text = textColorButton.text
                                colorDialog.open()
                        }
                        background: Rectangle {
                            color: textColorButton.text
                            border.color: "#CCCCCC"
                            border.width: 2
                            }
                        }
                    }
                }
                
                // 动画设置
                GridLayout {
                    Layout.fillWidth: true
                    columns: 3
                    columnSpacing: 12 * scaleFactor
                    rowSpacing: 12 * scaleFactor
                    
                    RowLayout {
                        Layout.preferredWidth: 120 * scaleFactor
                        spacing: 8 * scaleFactor
                        Text {
                            text: "启用动画："
                            font.pixelSize: 18 * scaleFactor
                        }
                        Switch {
                            id: animationSwitch
                            checked: true
                            onCheckedChanged: {
                                if (bubbleWrapper) {
                                    bubbleWrapper.animationDuration = checked ? animationDurationSlider.value : 0
                                }
                            }
                        }
                    }
                    Slider {
                        id: animationDurationSlider
                        from: 0
                        to: 2000
                        value: 300
                        Layout.fillWidth: true
                        Layout.preferredHeight: 45 * scaleFactor
                        onValueChanged: {
                            animationDurationLabel.text = Math.round(value) + " 毫秒"
                            if (bubbleWrapper && animationSwitch.checked) {
                                bubbleWrapper.animationDuration = Math.round(value)
                            }
                        }
                    }
                    Text {
                        id: animationDurationLabel
                        text: "300 毫秒"
                        font.pixelSize: 18 * scaleFactor
                        Layout.preferredWidth: 100 * scaleFactor
                    }
                }
                
                // 控制按钮
                GridLayout {
                    Layout.fillWidth: true
                    columns: 2
                    columnSpacing: 12 * scaleFactor
                    rowSpacing: 12 * scaleFactor
                    
                    Button {
                        id: showAtCursorButton
                        text: "显示气泡"
                        font.pixelSize: 18 * scaleFactor
                        Layout.fillWidth: true
                        Layout.preferredHeight: 60 * scaleFactor
                        onClicked: {
                            console.log("showAtCursorButton clicked")
                            if (!bubbleWrapper) {
                                console.log("Creating BubbleWrapper...")
                                createBubbleWrapper()
                            }
                            if (bubbleWrapper) {
                                // 在窗口右侧位置显示（绿框位置）
                                var rightX = root.width * 0.65  // 右侧65%位置
                                var centerY = root.height / 2   // 垂直居中
                                var cursorPos = Qt.point(rightX, centerY)
                                console.log("Calling showAt with pos=(" + rightX + "," + centerY + "), direction=" + directionCombo.currentIndex)
                                bubbleWrapper.showAt(cursorPos, directionCombo.currentIndex)
                            } else {
                                console.log("BubbleWrapper is null after creation attempt")
                            }
                        }
                    }
                    
                    Button {
                        text: "隐藏气泡"
                        font.pixelSize: 18 * scaleFactor
                        Layout.fillWidth: true
                        Layout.preferredHeight: 60 * scaleFactor
                        onClicked: {
                            if (bubbleWrapper) {
                                bubbleWrapper.hideAnimated()
                            }
                        }
                    }
                }
            }
        }
    }
    
    // 颜色选择对话框
    Popup {
        id: colorDialog
        width: 400 * scaleFactor
        height: 400 * scaleFactor
        modal: true
        focus: true
        anchors.centerIn: parent
        closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutside
        
        property var targetButton: null
        property bool isPenColor: false
        property bool isTextColor: false
        property string currentColor: "#000000"
        
        background: Rectangle {
            color: "#FFFFFF"
            border.color: "#CCCCCC"
            border.width: 2
            radius: 8
        }
        
        contentItem: ColumnLayout {
            spacing: 15 * scaleFactor
            anchors.margins: 20 * scaleFactor
            
            Text {
                text: "选择颜色"
                font.pixelSize: 20 * scaleFactor
                font.bold: true
                Layout.alignment: Qt.AlignHCenter
            }
            
            Text {
                text: "输入颜色值（格式：#RRGGBB）："
                font.pixelSize: 16 * scaleFactor
            }
            
            RowLayout {
                spacing: 10 * scaleFactor
                TextField {
                    id: colorInput
                        Layout.fillWidth: true
                    Layout.preferredHeight: 45 * scaleFactor
                    text: colorDialog.currentColor
                    font.pixelSize: 16 * scaleFactor
                    placeholderText: "#RRGGBB"
                    validator: RegExpValidator {
                        regExp: /^#[0-9A-Fa-f]{6}$/
                    }
                    onTextChanged: {
                        if (text.length === 7 && text.match(/^#[0-9A-Fa-f]{6}$/)) {
                            colorPreview.color = text
                        }
                    }
                }
                
                Rectangle {
                    id: colorPreview
                    Layout.preferredWidth: 60 * scaleFactor
                    Layout.preferredHeight: 45 * scaleFactor
                    color: colorInput.text.match(/^#[0-9A-Fa-f]{6}$/) ? colorInput.text : colorDialog.currentColor
                    border.color: "#CCCCCC"
                    border.width: 2
                }
            }
            
            Text {
                text: "或选择预设颜色："
                font.pixelSize: 16 * scaleFactor
            }
            
            ScrollView {
                Layout.fillWidth: true
                Layout.preferredHeight: 200 * scaleFactor
                
                GridLayout {
                    columns: 6
                    columnSpacing: 8 * scaleFactor
                    rowSpacing: 8 * scaleFactor
                    
                    Repeater {
                        model: [
                            "#DBBA92", "#000000", "#FFFFFF", "#FF0000", "#00FF00", "#0000FF",
                            "#FFFF00", "#FF00FF", "#00FFFF", "#808080", "#FFA500", "#800080",
                            "#FFC0CB", "#A52A2A", "#008000", "#000080", "#FF4500", "#9400D3"
                        ]
                        
                        Rectangle {
                            Layout.preferredWidth: 40 * scaleFactor
                            Layout.preferredHeight: 40 * scaleFactor
                            color: modelData
                            border.color: "#CCCCCC"
                            border.width: 1
                            
                            MouseArea {
                                anchors.fill: parent
                        onClicked: {
                                    colorInput.text = modelData
                                    colorPreview.color = modelData
                            }
                            }
                        }
                    }
                }
            }
            
            RowLayout {
                Layout.alignment: Qt.AlignRight
                spacing: 10 * scaleFactor
                
                Button {
                    text: "取消"
                    Layout.preferredWidth: 80 * scaleFactor
                    Layout.preferredHeight: 40 * scaleFactor
                    onClicked: colorDialog.close()
                }
                
                Button {
                    text: "确定"
                    Layout.preferredWidth: 80 * scaleFactor
                    Layout.preferredHeight: 40 * scaleFactor
                    onClicked: {
                        var newColor = colorInput.text
                        if (newColor.match(/^#[0-9A-Fa-f]{6}$/)) {
                            if (colorDialog.targetButton) {
                                colorDialog.targetButton.text = newColor
                            }
        if (bubbleWrapper && bubbleWrapper.bubbleWidget) {
                                if (colorDialog.isPenColor) {
                bubbleWrapper.bubbleWidget.penColor = newColor
                                } else if (colorDialog.isTextColor) {
                bubbleWrapper.bubbleWidget.textColor = newColor
            } else {
                bubbleWrapper.bubbleWidget.brushColor = newColor
                                }
                            }
                            colorDialog.close()
                        } else {
                            // 显示错误提示
                            console.log("颜色格式错误，请输入 #RRGGBB 格式")
                        }
                    }
                }
            }
        }
    }
}
